package com.caituo.idouyou.user.test;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;


/**
 * @author fisher
 * @description Action公共基类
 * @param <T>所有对象类型
 */

public abstract class BaseAction<T> extends ActionSupport implements
		ModelDriven<T>, Preparable, SessionAware, ServletRequestAware,
		ServletResponseAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected Log log = LogFactory.getLog(getClass());

	// -- header 常量定义 --//
	private static final String HEADER_ENCODING = "encoding";
	private static final String HEADER_NOCACHE = "no-cache";
	private static final String DEFAULT_ENCODING = "UTF-8";
	private static final boolean DEFAULT_NOCACHE = true;

	// -- Content Type 定义 --//
	public static final String TEXT_TYPE = "text/plain";
	public static final String JSON_TYPE = "application/json";
	public static final String XML_TYPE = "text/xml";
	public static final String HTML_TYPE = "text/html";
	public static final String JS_TYPE = "text/javascript";
	public static final String EXCEL_TYPE = "application/vnd.ms-excel";
	public static final String IMG_TYPE = "image/jpeg";

	// -------------------- 作用域对象 --------------------//

	/** sessionMap对象 */
	private Map<String, Object> sessionMap;

	/** request对象 */
	private HttpServletRequest request;

	/** response对象 */
	private HttpServletResponse response;


	// --------------------视图跳转路径------------------//
	/**
	 * 例如:"index.jsp index.ftl"
	 */
	private String target;

	// -- Preparable函数 --//

	/**
	 * 实现空的prepare()函数,屏蔽了所有Action函数都会执行的公共的二次绑定.
	 */
	public void prepare() throws Exception {

	}

	// -------------绕过jsp/freemaker直接输出文本函数-------------//

	// -- 绕过jsp/freemaker直接输出文本的函数 --//
	/**
	 * 直接输出内容的简便函数. eg. render("text/plain", "hello", "encoding:GBK");
	 * render("text/plain",hello", "no-cache:false");
	 * render("text/plain","hello", "encoding:GBK","no-cache:false");
	 * 
	 * @param headers
	 *            可变的header数组，目前接受的值为"encoding:"或"no-cache:",默认值分别为UTF-8和true.
	 */
	public static void render(final String contentType, final String content,
			final String... headers) {
		HttpServletResponse response = initResponseHeader(contentType, headers);
		try {
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public static void renderImg(final String img, final String... headers) {
		render(IMG_TYPE, img, headers);
	}

	/**
	 * 直接输出文本.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderText(final String text, final String... headers) {
		render(TEXT_TYPE, text, headers);
	}

	/**
	 * 直接输出HTML.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderHtml(final String html, final String... headers) {
		render(HTML_TYPE, html, headers);
	}

	/**
	 * 直接输出XML.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderXml(final String xml, final String... headers) {
		render(XML_TYPE, xml, headers);
	}

	/**
	 * 直接输出JSON.
	 * 
	 * @param jsonString
	 *            json字符串.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final String jsonString,
			final String... headers) {
		render(JSON_TYPE, jsonString, headers);
	}

	/**
	 * 直接输出JSON,使用fastJson转换Java对象.
	 * 
	 * @param data
	 *            可以是List<POJO>, POJO[], POJO, 也可以Map名值对.
	 * @see #render(String, String, String...)
	 */
	
	

	/**
	 * 分析并设置contentType与headers.
	 */
	private static HttpServletResponse initResponseHeader(
			final String contentType, final String... headers) {
		// 分析headers参数
		String encoding = DEFAULT_ENCODING;
		boolean noCache = DEFAULT_NOCACHE;

		for (String header : headers) {
			String headerName = StringUtils.substringBefore(header, ":");
			String headerValue = StringUtils.substringAfter(header, ":");

			if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
				encoding = headerValue;
			} else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
				noCache = Boolean.parseBoolean(headerValue);
			} else {
				throw new IllegalArgumentException(headerName
						+ "不是一个合法的header类型");
			}
		}

		HttpServletResponse response = ServletActionContext.getResponse();

		// 设置headers参数
		String fullContentType = contentType + ";charset=" + encoding;
		response.setContentType(fullContentType);
		if (noCache) {
			// Http 1.0 header
			response.setDateHeader("Expires", 1L);
			response.addHeader("Pragma", "no-cache");
			// Http 1.1 header
			response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
		}

		return response;
	}

	/**
	 * @description 获取磁盘物理路径
	 * @return String
	 */
	protected String getRealPath() {
		return request.getSession().getServletContext().getRealPath("");
	}

	/**
	 * @description 得到session对象
	 * @return Session
	 */
	protected HttpSession getSession() {
		return this.request.getSession();
	}

	/**
	 * @Title: getParams
	 * @Description: 得到页面所有参数
	 * @return Map<String,Object>
	 * @throws
	 */
	public Map<String, Object> getParameters() {
		return ActionContext.getContext().getParameters();
	}

	/**
	 * @description 设置session对象Attribute属性
	 * @param key
	 * @param value
	 */
	protected void setSessionAttribute(String key, Object value) {
		sessionMap.put(key, value);
	}

	/**
	 * @description 返回session对象的Attribute属性
	 * @param key
	 * @return Object
	 */
	protected Object getSessionAttribute(String key) {
		return sessionMap.get(key);
	}

	/**
	 * @description 清除整个session
	 */
	protected void clearSession() {
		sessionMap.clear();
	}

	/**
	 * @description 清除session中指定的内容
	 * @param key
	 */
	protected void remove(Object key) {
		sessionMap.remove(key);
	}

	/**
	 * @description 通过request获取页面参数值
	 * @return string
	 */
	protected String getParameters(String name) {
		return (null != request.getParameter(name)) ? request
				.getParameter(name) : null;
	}

	/**
	 * @description 获取项目根目录
	 * @return String
	 */
	protected String getRootPath() {
		return request.getContextPath();
	}

	/**
	 * @description 获取request独享
	 * @return
	 */

	public HttpServletRequest getRequest() {
		return request;
	}

	/**
	 * @description 获取response对象
	 * @return
	 */

	public HttpServletResponse getResponse() {
		return response;
	}

	/**
	 * @description 获取sessionMap
	 * @return
	 */

	public Map<String, Object> getSessionMap() {
		return sessionMap;
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;

	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;

	}

	public void setSession(Map<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}
}
